package com.xbjtech.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.xbjtech.model.Role;
import com.xbjtech.model.RoleExample;
import com.xbjtech.model.RoleExample.Criteria;
import com.xbjtech.model.vo.RoleVO;
import com.xbjtech.service.RoleService;
import com.xbjtech.util.ResponseBean;

import lombok.extern.slf4j.Slf4j;

/**
* @author sparkCat E-mail:2925365275@qq.com
* @version 创建时间：2019年2月9日 下午7:38:05
* 类说明
*/
@Controller
@RequestMapping("/role")
@Slf4j
public class RoleController {

	@Autowired
	private RoleService roleService;
	
	@RequestMapping("/list")
	public String list() {
		return "role/list";
	}
	
	@RequestMapping("/page")
	@ResponseBody
	public Map<String, Object> page(
			Role role,
			@RequestParam(required = false, defaultValue = "1") Integer page, 
			@RequestParam(required = false, defaultValue = "10")Integer rows) {
		log.info("roleVO:{}", role);
		RoleExample example = new RoleExample();
		example.setOrderByClause("id desc");
		Criteria criteria = example.createCriteria();
		if (null != role.getName() && !role.getName().isEmpty()) {
			criteria.andNameLike("%"+role.getName()+"%");
		}
		if (null != role.getRole() && !role.getRole().isEmpty()) {
			criteria.andRoleLike("%"+role.getRole()+"%");
		}
		List<RoleVO> list = roleService.list(example, page, rows);
		PageInfo<RoleVO> pageInfo = new PageInfo<>(list);
		Map<String, Object> map = new HashMap<>();
		map.put("total", pageInfo.getTotal());
		map.put("rows", pageInfo.getList());
		return map;
	}
	
	@PostMapping("/save")
	@ResponseBody
	public ResponseBean save(RoleVO roleVO) {
		log.info("roleVO:{}", roleVO);
		try {
			if (roleVO.getId() == null) {
				roleService.insertRole(roleVO);;
				return new ResponseBean(true, "保存成功");
			} else {
				roleService.updateRole(roleVO);;
				return new ResponseBean(true, "更新成功");
			}
		} catch (Exception e) {
			log.error("RoleController.save() throws a exception -> {}", e.getMessage());
		}
		return new ResponseBean(false, "操作失败");
	}
	
	@PostMapping("/delete")
	@ResponseBody
	public ResponseBean delete(Long id) {
		try {
			roleService.deleteRoleById(id);
			return new ResponseBean(true, "删除成功");
		} catch (Exception e) {
			log.error("{}", e.getMessage());
		}
		return new ResponseBean(false, "删除失败");
	}
}
